import { login, getCode } from '@/store/actions/login'
import { Button, NavBar, Form, Input, Toast } from 'antd-mobile'
import { AxiosError } from 'axios'
import { useRef, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory, useLocation } from 'react-router-dom'
import { InputRef } from 'antd-mobile/es/components/input'

import styles from './index.module.scss'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const [timeLeft, setTimeLeft] = useState(0)
  const timeRef = useRef(-1)
  const location = useLocation<{ from: string } | undefined>()
  type LoginForm = {
    mobile: string
    code: string
  }
  // 登录
  const onFinish = async (value: LoginForm) => {
    try {
      await dispatch(login(value))
      Toast.show({
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          if (location.state) {
            return history.replace(location.state.from)
          }
          history.replace('/home/index')
        },
      })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({
        content: error.response?.data?.message,
        duration: 1000,
      })
    }
  }
  //发验证码
  const onGetCode = () => {
    const mobile = form.getFieldValue('mobile')

    // console.log(mobile)

    const hasError = form.getFieldError('mobile').length > 0
    if (!mobile || hasError) {
      return mobileRef.current?.focus()
    }
    dispatch(getCode(mobile))
    setTimeLeft(5)
    timeRef.current = window.setInterval(() => {
      setTimeLeft((timeLeft) => timeLeft - 1)
    }, 1000)
  }
  useEffect(() => {
    if (timeLeft === 0) {
      clearInterval(timeRef.current)
    }
  }, [timeLeft])
  useEffect(() => {
    return () => {
      clearInterval(timeRef.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form onFinish={onFinish} form={form}>
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input
              placeholder="请输入手机号"
              maxLength={11}
              type="number"
              ref={mobileRef}
            />
          </Form.Item>

          <Form.Item
            name="code"
            className="login-item"
            rules={[
              { required: true, message: '请输入验证码' },
              { pattern: /^\d{6}$/, message: '验证码格式不正确' },
            ]}
            extra={
              <span
                className="code-extra"
                onClick={timeLeft === 0 ? onGetCode : undefined}
              >
                {timeLeft === 0 ? '发送验证码' : `${timeLeft}s后重新获取`}
              </span>
            }
          >
            <Input
              placeholder="请输入验证码"
              autoComplete="off"
              maxLength={6}
              type="number"
            />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              const disabled =
                form.getFieldsError().filter((item) => item.errors.length > 0)
                  .length > 0 || !form.isFieldsTouched(true)
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                  disabled={disabled}
                >
                  登 录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
